package com.lvmama.dashboard.rop.service.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lvmama.dashboard.core.annotation.AjaxMethod;
import com.lvmama.dashboard.entity.UserUser;
import com.lvmama.dashboard.model.page.ResultHandler;
import com.lvmama.dashboard.model.rop.AjaxRequest;
import com.lvmama.dashboard.model.rop.AjaxRequestBody;
import com.lvmama.dashboard.model.rop.AjaxResponse;
import com.lvmama.dashboard.model.rop.user.request.UserLoginRequest;
import com.lvmama.dashboard.model.rop.user.response.UserInfoResponse;
import com.lvmama.dashboard.service.ajax.user.IRopUserUserService;
import com.lvmama.dashboard.service.user.IUserUserService;
import com.lvmama.dashboard.utils.ServletUtils;
import com.lvmama.java.rhino.spark.utils.Constants;
import com.lvmama.java.rhino.spark.utils.copy.CachedBeanCopier;

@Component("ropUserUserService")
public class RopUserUserServiceImpl implements IRopUserUserService {
	@Autowired
	private IUserUserService userUserService;
	@Autowired
	private CachedBeanCopier beanCopier;
	
	@Override
	@AjaxMethod(ajaxmethod = "com.lvtu.dashboard.api.login")
	public AjaxResponse<UserInfoResponse> login(AjaxRequestBody<UserLoginRequest> requestBody) {
		UserLoginRequest request = requestBody.getT();
		
		ResultHandler<UserUser> result = userUserService.login(request.getUsername(), request.getPassword());
		AjaxResponse<UserInfoResponse> responseBody = new AjaxResponse<UserInfoResponse>();
		if(!result.isSuccess()) {
			responseBody.setCode(Constants.CODE.ERROR.getCode());
			responseBody.setMessage(result.getMessage());
			return responseBody;
		}
		UserUser user = result.getData();
		ServletUtils.putSession(request.getLogsessionid(), Constants.SESSION_USER_KEY, user);
		
		UserInfoResponse response = beanCopier.copy(user, UserInfoResponse.class);
		responseBody.setData(response);
		
		return responseBody;
	}
	
	@Override
	@AjaxMethod(ajaxmethod = "com.lvtu.dashboard.api.getUser")
	public AjaxResponse<UserInfoResponse> getUser(AjaxRequestBody<AjaxRequest> requestBody) {
		String logsessionid = requestBody.getT().getLogsessionid();
		UserUser user = ServletUtils.getUser(logsessionid);
		UserInfoResponse response = beanCopier.copy(user, UserInfoResponse.class);
		AjaxResponse<UserInfoResponse> responseBody = new AjaxResponse<UserInfoResponse>();
		responseBody.setData(response);
		return responseBody;
	}

	@Override
	@AjaxMethod(ajaxmethod = "com.lvtu.dashboard.api.logout")
	public AjaxResponse<Object> logout(AjaxRequestBody<AjaxRequest> requestBody) {
		String logsessionid = requestBody.getT().getLogsessionid();
		ServletUtils.removeFromSession(logsessionid, Constants.SESSION_USER_KEY);
		return new AjaxResponse<Object>();
	}
}
